package com.zat.mes.andrmes.retrofit.callback

import android.widget.Toast
import com.zat.mes.andrmes.BaseApplication
import com.zat.mes.andrmes.BaseApplication.Companion.appContext
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.event.LoadingEventMessage
import org.greenrobot.eventbus.EventBus
import org.json.JSONException
import retrofit2.Call
import retrofit2.Callback
import retrofit2.HttpException
import retrofit2.Response
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException


/**
 * @author zy
 * @date :2020-02-05 13:23
 * @description: http 请求统一处理
 */
abstract class MesCallBack<T> : Callback<T> {

    override fun onFailure(call: Call<T>, t: Throwable) {
        onFail(call, t)
        EventBus.getDefault().post(LoadingEventMessage())
    }

    override fun onResponse(call: Call<T>, response: Response<T>) {
        onSuccessful(call, response)
    }

    abstract fun onSuccessful(
        call: Call<T>?,
        response: Response<T>?
    )

    protected fun onFail(
        call: Call<T>?,
        t: Throwable
    ) {
        var msg: String
        //对异常进行判断，这个是我随便写的一点，可以写一个工具类给封装起来
        msg = when (t) {
            is SocketTimeoutException -> BaseApplication.getContext().getString(R.string.net_overtime)
            is ConnectException -> BaseApplication.getContext().getString(R.string.net_server_exception)
            is HttpException -> {
                when (t.code()) {
                    404 -> BaseApplication.getContext().getString(R.string.net_server_exception)
                    500 -> BaseApplication.getContext().getString(R.string.net_server_exception)
                    else -> t.message()
                }
            }
            is JSONException -> BaseApplication.getContext().getString(R.string.json_exception)
            is UnknownHostException -> BaseApplication.getContext().getString(R.string.net_exception)
            else -> t.message.toString()
        }
        Toast.makeText(appContext, msg, Toast.LENGTH_SHORT).show()
    }
}